{{define "dashboard-default/server"}}
{{template "common/header" .}}
{{template "common/menu" .}}
<div class="nb-container">
    <div class="ui container">
        <div class="ui grid">
            <div class="right floated right aligned twelve wide column">
                <button class="ui right labeled server-primary-btn icon button" onclick="batchEditServerGroup()"><i
                        class="edit icon"></i> {{tr "BatchEditServerGroup"}}
                </button>
                <button class="ui right labeled server-primary-btn icon button" onclick="batchDeleteServer()"><i
                        class="trash icon"></i> {{tr "BatchDeleteServer"}}
                </button>
                <button class="ui right labeled server-primary-btn icon button" onclick="addOrEditServer()"><i
                        class="add icon"></i> {{tr "AddServer"}}
                </button>
                <button class="ui right labeled server-primary-btn icon button" onclick="forceUpdate()"><i
                        class="arrow alternate circle up outline icon"></i> {{tr "ForceUpdate"}}
                </button>
            </div>
        </div>
        <table class="ui very basic table">
            <thead>
                <tr>
                    <th><button onclick="checkAllServer()" class="ui mini server-primary-btn button">{{tr
                            "SelectAll"}}</button></th>
                    <th>ID({{tr "DisplayIndex"}})</th>
                    <th>{{tr "Name"}}</th>
                    <th>{{tr "ServerGroup"}}</th>
                    <th>{{tr "IPAddress"}}</th>
                    <th>{{tr "VersionNumber"}}</th>
                    <th>{{tr "HideForGuest"}}</th>
                    <th>{{tr "EnableDDNS"}}</th>
                    <th>{{tr "CopySecret"}}</th>
                    <th>{{tr "OneKeyInstall"}}</th>
                    <th>{{tr "Note"}}</th>
                    <th>{{tr "PublicNote"}}</th>
                    <th>{{tr "Administration"}}</th>
                </tr>
            </thead>
            <tbody>
                {{range $server := .Servers}}
                <tr>
                    <td><input type="checkbox" class="server-servers" value="{{$server.ID}}" /></td>
                    <td>{{$server.ID}}({{$server.DisplayIndex}})</td>
                    <td>{{$server.Name}}</td>
                    <td>{{$server.Tag}}</td>
                    <td>
                        IP:{{$server.Host.IP}}
                        <button class="ui icon mini button" data-clipboard-text="{{$server.Host.IP}}" data-tooltip="{{tr "ClickToCopy"}}" style="margin-left: 5px;">
                            <i class="copy icon"></i>
                        </button>
                    </td>
                    <td>{{$server.Host.Version}}</td>
                    <td>{{$server.HideForGuest}}</td>
                    <td>{{$server.EnableDDNS}}</td>
                    <td>
                        <button class="ui icon mini button" data-clipboard-text="{{$server.Secret}}"
                            data-tooltip="{{tr "ClickToCopy"}}">
                            <i class="copy icon"></i>
                        </button>
                    </td>
                    <td>
                        <div class="ui mini icon buttons">
                            <button class="ui icon mini button linux-install-btn" data-server-id="{{$server.ID}}" data-secret="{{$server.Secret}}" data-server-ip="{{if $server.Host}}{{$server.Host.IP}}{{end}}" data-tooltip="{{tr "ClickToCopy"}}">
                                <i class="linux icon"></i>
                            </button>
                            <button class="ui icon mini button" data-clipboard-text="{{if $.Conf.GRPCHost}}[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Ssl3 -bor [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12;set-ExecutionPolicy RemoteSigned;Invoke-WebRequest https://fastly.jsdelivr.net/gh/xos/serverstatus@master/script/server-status.ps1 -OutFile C:\server-status.ps1;powershell.exe C:\server-status.ps1 {{$.Conf.GRPCHost}}:{{if $.Conf.ProxyGRPCPort}}{{$.Conf.ProxyGRPCPort}}{{else}}{{$.Conf.GRPCPort}}{{end}} {{$server.Secret}}{{if $.Conf.TLS}} --tls{{end}}{{else}}{{tr "NoDomainAlert"}}{{end}}" data-tooltip="{{tr "ClickToCopy"}}">
                                <i class="windows icon"></i>
                            </button>
                        </div>
                    </td>
                    <!-- <td style="word-break: break-word; white-space: pre-wrap;">{{$server.Note}}</td> -->
                    <td>
                        {{if $server.Note}}
                            <button class="ui icon mini button" title="{{ $server.Note }}" onclick="addOrEditServer({{$server.MarshalForDashboard}})"><i class="sticky note icon"></i></button>
                        {{end}}
                    </td>
                    <td>
                        {{if $server.PublicNote}}
                            <button class="ui icon mini button" title="{{$server.PublicNote}}" onclick="addOrEditServer({{$server.MarshalForDashboard}})"><i class="sticky clipboard icon"></i></button>
                        {{end}}
                    </td>
                    <td>
                        <div class="ui mini icon buttons">
                            <button class="ui button" onclick="connectToServer({{$server.ID}})">
                                <i class="terminal icon"></i>
                            </button>
                            <button class="ui button" onclick="addOrEditServer({{$server.MarshalForDashboard}})">
                                <i class="edit icon"></i>
                            </button>
                            <button class="ui button" onclick="showConfirm('{{tr "DeleteServer"}}'+'[{{$server.Name}}]','{{tr "ConfirmToDeleteThisServer"
                                }}',deleteRequest,'/api/server/'+{{$server.ID}})">
                                <i class="trash alternate outline icon"></i>
                            </button>
                        </div>
                    </td>
                </tr>
                {{end}}
            </tbody>
        </table>
    </div>
</div>
{{template "component/server" .}}
{{template "common/footer" .}}
<script src="https://s4.zstatic.net/ajax/libs/clipboard.js/2.0.11/clipboard.min.js"></script>
<script>
    // 服务器IP地址检测和脚本切换功能
    const serverLocationCache = new Map();

    // 解析多个IP地址，优先选择IPv4
    function parseServerIPs(serverIPString) {
        if (!serverIPString || serverIPString.trim() === '') {
            return null;
        }

        // 分割多个IP地址（可能用/、,、;、空格等分隔）
        const ipList = serverIPString.split(/[\/,;\s]+/).filter(ip => ip.trim() !== '');

        // IPv4正则表达式
        const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/;
        // IPv6正则表达式（简化版）
        const ipv6Regex = /^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/;

        const ipv4List = [];
        const ipv6List = [];

        // 分类IPv4和IPv6地址
        for (const ip of ipList) {
            const cleanIP = ip.trim();
            if (ipv4Regex.test(cleanIP)) {
                ipv4List.push(cleanIP);
            } else if (ipv6Regex.test(cleanIP)) {
                ipv6List.push(cleanIP);
            }
        }

        // 优先返回第一个IPv4，如果没有IPv4则返回第一个IPv6
        if (ipv4List.length > 0) {
            console.log(`从多个IP中选择IPv4: ${ipv4List[0]} (全部IP: ${serverIPString})`);
            return ipv4List[0];
        } else if (ipv6List.length > 0) {
            console.log(`从多个IP中选择IPv6: ${ipv6List[0]} (全部IP: ${serverIPString})`);
            return ipv6List[0];
        } else {
            console.warn(`无法解析有效IP地址: ${serverIPString}`);
            return null;
        }
    }

    // 检测服务器IP地址所在地区
    async function detectServerLocation(serverIPString) {
        // 解析出优先IP地址
        const serverIP = parseServerIPs(serverIPString);

        if (!serverIP) {
            console.warn(`无法解析服务器IP地址: ${serverIPString}`);
            return 'DEFAULT';
        }

        // 检查缓存
        if (serverLocationCache.has(serverIP)) {
            return serverLocationCache.get(serverIP);
        }

        try {
            const response = await fetch(`https://ipapi.co/${serverIP}/json/`);
            const data = await response.json();
            const countryCode = data.country_code;
            console.log(`检测到服务器 ${serverIP} 地区:`, countryCode);

            // 缓存结果
            serverLocationCache.set(serverIP, countryCode);
            return countryCode;
        } catch (error) {
            console.warn(`服务器 ${serverIP} IP地址检测失败，使用默认设置(gitee):`, error);
            // 缓存默认结果
            serverLocationCache.set(serverIP, 'DEFAULT');
            return 'DEFAULT';
        }
    }

    // 生成安装脚本
    async function generateInstallScript(secret, serverIP) {
        const host = '{{.Conf.GRPCHost}}';
        const port = '{{if .Conf.ProxyGRPCPort}}{{.Conf.ProxyGRPCPort}}{{else}}{{.Conf.GRPCPort}}{{end}}';
        const tls = '{{if .Conf.TLS}} --tls{{end}}';

        if (!host) {
            return '{{tr "NoDomainAlert"}}';
        }

        // 默认使用gitee，只有明确检测到非中国大陆服务器才使用github
        let baseUrl = 'https://gitee.com/ten/ServerStatus/raw/master'; // 默认gitee

        // 如果有服务器IP，检测服务器IP所在地区
        if (serverIP && serverIP.trim() !== '') {
            const serverLocation = await detectServerLocation(serverIP);

            // 只有明确检测到非中国大陆服务器才使用github
            if (serverLocation && serverLocation !== 'CN' && serverLocation !== 'DEFAULT') {
                baseUrl = 'https://raw.githubusercontent.com/xos/serverstatus/master';
                console.log(`服务器 ${serverIP} 位于 ${serverLocation}，使用github链接`);
            } else {
                console.log(`服务器 ${serverIP} 位于中国大陆或检测失败，使用gitee链接`);
            }
        } else {
            console.log('无服务器IP信息，使用默认gitee链接');
        }

        return `curl -L ${baseUrl}/script/server-status.sh -o server-status.sh && chmod +x server-status.sh && sudo ./server-status.sh install_agent ${host} ${port} ${secret}${tls}`;
    }

    // 初始化剪贴板功能
    function initClipboard() {
        // 为Linux安装按钮设置动态剪贴板文本
        const linuxButtons = document.querySelectorAll('.linux-install-btn');
        linuxButtons.forEach(button => {
            button.addEventListener('click', async function() {
                const secret = this.getAttribute('data-secret');
                const serverIP = this.getAttribute('data-server-ip');

                if (!serverIP || serverIP.trim() === '') {
                    console.warn('未找到服务器IP地址，使用默认gitee链接');
                    // 使用默认的gitee链接
                    const script = await generateInstallScript(secret, null);

                    // 复制到剪贴板
                    try {
                        await navigator.clipboard.writeText(script);
                        console.log('安装脚本已复制到剪贴板（默认gitee）');
                    } catch (err) {
                        console.error('复制失败:', err);
                        // 降级处理
                        const textArea = document.createElement('textarea');
                        textArea.value = script;
                        document.body.appendChild(textArea);
                        textArea.select();
                        document.execCommand('copy');
                        document.body.removeChild(textArea);
                    }
                    return;
                }

                const script = await generateInstallScript(secret, serverIP);

                // 复制到剪贴板
                try {
                    await navigator.clipboard.writeText(script);
                    console.log('安装脚本已复制到剪贴板');
                } catch (err) {
                    console.error('复制失败:', err);
                    // 降级处理
                    const textArea = document.createElement('textarea');
                    textArea.value = script;
                    document.body.appendChild(textArea);
                    textArea.select();
                    document.execCommand('copy');
                    document.body.removeChild(textArea);
                }
            });
        });
    }

    // 初始化其他剪贴板按钮（Windows等）
    var clipboard = new ClipboardJS('.ui.icon.mini.button:not(.linux-install-btn)');

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        initClipboard();
    });

    const checkBoxList = document.querySelectorAll('tbody > tr > td > input.server-servers[type=checkbox]')

    function checkAllServer() {
        checkBoxList.forEach(cb => {
            cb.checked = true
        })
    }

    function forceUpdate() {
        const servers = []
        checkBoxList.forEach(cb => {
            if (cb.checked) {
                servers.push(parseInt(cb.value))
            }
        })
        if (servers.length == 0) {
            $.suiAlert({
                title: '{{tr "NoServerSelected"}}',
                description: '',
                type: 'warning',
                time: '2',
                position: 'top-center',
            });
            return
        }
        $.post('/api/force-update', JSON.stringify(servers), null, 'application/json')
            .then((resp) => {
                if (resp.code == 200) {
                    $.suiAlert({
                        title: '{{tr "ExecutionResults"}}',
                        description: resp.message,
                        type: 'success',
                        time: '3',
                        position: 'top-center',
                    });
                } else {
                    $.suiAlert({
                        title: '',
                        description: resp.message,
                        type: 'error',
                        time: '3',
                        position: 'top-center',
                    });
                }
            }).catch(err => {
                let errorMessage = '网络错误';
                if (err && err.responseText) {
                    errorMessage = '网络错误：' + err.responseText;
                } else if (err && err.message) {
                    errorMessage = err.message;
                } else if (typeof err === 'string') {
                    errorMessage = err;
                }
                $.suiAlert({
                    title: '强制更新失败',
                    description: errorMessage,
                    type: 'error',
                    time: '3',
                    position: 'top-center',
                });
            })
    }
    function batchEditServerGroup() {
        let groupName = prompt('{{tr "InputServerGroupName"}}')
        if (groupName === null) {
            return
        }
        const servers = []
        checkBoxList.forEach(cb => {
            if (cb.checked) {
                servers.push(parseInt(cb.value))
            }
        })
        if (servers.length == 0) {
            $.suiAlert({
                title: '{{tr "NoServerSelected"}}',
                description: '',
                type: 'warning',
                time: '2',
                position: 'top-center',
            });
            return
        }
        $.post('/api/batch-update-server-group', JSON.stringify({ servers: servers, group: groupName }))
            .then((resp) => {
                if (resp.code == 200) {
                    $.suiAlert({
                        title: '{{tr "ExecutionResults"}}',
                        description: resp.message,
                        type: 'success',
                        time: '3',
                        position: 'top-center',
                    });
                    window.location.reload()
                } else {
                    $.suiAlert({
                        title: '',
                        description: resp.message,
                        type: 'error',
                        time: '3',
                        position: 'top-center',
                    });
                }
            }).catch(err => {
                let errorMessage = '网络错误';
                if (err && err.responseText) {
                    errorMessage = '网络错误：' + err.responseText;
                } else if (err && err.message) {
                    errorMessage = err.message;
                } else if (typeof err === 'string') {
                    errorMessage = err;
                }
                $.suiAlert({
                    title: '批量编辑失败',
                    description: errorMessage,
                    type: 'error',
                    time: '3',
                    position: 'top-center',
                });
            })
    }
    function batchDeleteServer() {
        const servers = []
        console.log('开始构建服务器ID数组');
        console.log('找到的复选框数量:', checkBoxList.length);
        
        checkBoxList.forEach((cb, index) => {
            console.log(`复选框 ${index}:`, {
                checked: cb.checked,
                value: cb.value,
                parsedValue: parseInt(cb.value),
                isNaN: isNaN(parseInt(cb.value))
            });
            
            if (cb.checked) {
                const serverId = parseInt(cb.value);
                if (!isNaN(serverId)) {
                    servers.push(serverId);
                    console.log(`添加服务器ID: ${serverId}`);
                } else {
                    console.error('无效的服务器ID:', cb.value);
                }
            }
        })
        
        console.log('最终的服务器数组:', servers);
        console.log('数组JSON表示:', JSON.stringify(servers));
        
        if (servers.length == 0) {
            $.suiAlert({
                title: '{{tr "NoServerSelected"}}',
                description: '',
                type: 'warning',
                time: '2',
                position: 'top-center',
            });
            return
        }
        showConfirm('{{tr "DeleteServer"}}', '{{tr "ConfirmToDeleteServer"}}', () => postJson('/api/batch-delete-server', servers), '')
    }
</script>
{{end}}
